//
//  TTWeChatManager.m
//  ExhibitionHall
//
//  Created by 王洋 on 2019/6/11.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "TTWeChatManager.h"
#import <WechatAuthSDK.h>
#import "AFNetworking.h"

@implementation TTWeChatManager

+ (void)initWechatSDK {
    
}


+ (void)getWechatAccessToken:(void(^)(NSString *token))completHandle {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.requestSerializer.timeoutInterval = 10.0;
    
    NSDictionary *dict = @{
                           @"grant_type":@"client_credential",
                           @"appid":TT_wxAppID,
                           @"secret":TT_wxAppSecret
                           };
    NSString *url = @"https://api.weixin.qq.com/cgi-bin/token";
    
    [manager GET:url parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *jsonDict = [Utilities dictionaryWithJsonString:responseObject];
        NSString *token = [jsonDict valueForKey:@"access_token"];
        completHandle(token);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

+ (void)getWechatTicketWithToken:(NSString *)token complet:(nonnull void (^)(NSString * _Nonnull))completHandle{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.requestSerializer.timeoutInterval = 10.0;
    
    NSDictionary *dict = @{
                           @"access_token":token,
                           @"type":@(2)
                           };
    
    NSString *url = @"https://api.weixin.qq.com/cgi-bin/ticket/getticket";
    
    [manager GET:url parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *jsonDict = [Utilities dictionaryWithJsonString:responseObject];
        
        NSString *ticket = [jsonDict valueForKey:@"ticket"];
        completHandle(ticket);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

+ (void)getWechatSignatureComplete:(void(^)(NSString *signStr, NSString *timeStr))completHandle {

    [self getWechatAccessToken:^(NSString * _Nonnull token) {
       
        [self getWechatTicketWithToken:token complet:^(NSString * _Nonnull ticket) {
           
            NSString *timeStr = [NSString stringWithFormat:@"%.0f",[NSDate date].timeIntervalSince1970];
            NSString *sinStr = [[NSString stringWithFormat:@"appid=%@&noncestr=%@&sdk_ticket=%@&timestamp=%@",TT_wxAppID,timeStr,ticket,timeStr]sha1];
            
            completHandle(sinStr,timeStr);
        }];
    }];
}



@end
